package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerChuKuQingKuangComponent;
import com.example.administrator.printoutindemo.di.module.ChuKuQingKuangModule;
import com.example.administrator.printoutindemo.mvp.contract.ChuKuQingKuangContract;
import com.example.administrator.printoutindemo.mvp.presenter.ChuKuQingKuangPresenter;
import com.example.administrator.printoutindemo.mvp.ui.adapter.ChuKuQingKuangAdapter;
import com.example.administrator.printoutindemo.mvp.ui.entity.ChuKuQingKuang;
import com.example.administrator.printoutindemo.mvp.ui.entity.SearchOutStorageListForLeader;
import com.example.administrator.printoutindemo.mvp.ui.entity.ZuiXinXiaoXi;
import com.example.administrator.printoutindemo.mvp.ui.view.ChuKuQingKuangRightSideslipLay;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.utils.PrinterUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_CHU_KU_QING_KUANG)
public class ChuKuQingKuangActivity extends BaseActivity<ChuKuQingKuangPresenter> implements ChuKuQingKuangContract.View, ChuKuQingKuangRightSideslipLay.FlowingDrawerInterface, OnRefreshListener, OnLoadMoreListener, ChuKuQingKuangAdapter.IChuKuQingKuangAdapter, PrinterUtil.PrinterI {


    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawer;
    @BindView(R.id.nav_view)
    LinearLayout navigationView;
    @BindView(R.id.btnRight)
    TextView mBtnRight;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    PrinterUtil mPrinterUtil;
    private ChuKuQingKuangRightSideslipLay menuHeaderView;
    private RecyclerView recyclerView;
    private ChuKuQingKuangAdapter mAdapter;
    private List<SearchOutStorageListForLeader> mSearchOutStorageListForLeaders = new ArrayList<>();
    private String mSid = "";
    private String mProid = "";
    private String mProjectName = "";
    private String mPurchaseid = "";
    private String mMaterial = "";
    private String mSuppliername = "";
    private String mTargetproject = "";
    private String mOutBeginTime = "";
    private String mOutEndTime = "";
    private String mChuKuQingKuangType = "";
    private String methodName = "SearchOutStorageListForLeaderPaging";
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), mSid, mProid, mProjectName, mPurchaseid, mMaterial, mSuppliername, mTargetproject, mOutBeginTime, mOutEndTime);
        mRefreshLayout.finishLoadMore();
    }

    private void getData(String user_id, String sid, String proid, String projectname, String purchaseid, String material, String suppliername, String targetproject, String outBeginTime, String outEndTime) {

        showLoading();
//        String methodName = "SearchOutStorageListForLeader";
        if (mChuKuQingKuangType.equals("ld")) {
            methodName = "SearchOutStorageListForLeaderPaging";
        } else if (mChuKuQingKuangType.equals("cgy")) {
            methodName = "SearchOutStorageListForCgyPaging";
        }

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("sid", sid);
        params.put("proid", proid);
        params.put("projectname", projectname);
        params.put("purchaseid", purchaseid);
        params.put("material", material);
        params.put("suppliername", suppliername);
        params.put("targetproject", targetproject);
        params.put("outBeginTime", outBeginTime);
        params.put("outEndTime", outEndTime);
        params.put("startIndex", String.valueOf(mStart));
        params.put("endIndex", String.valueOf(mStart + mNum - 1));

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {


                    List<SearchOutStorageListForLeader> searchOutStorageListForLeaders = new Gson().fromJson(result, new TypeToken<List<SearchOutStorageListForLeader>>() {
                    }.getType());

                    if (searchOutStorageListForLeaders != null && searchOutStorageListForLeaders.size() > 0) {
                        mStart += searchOutStorageListForLeaders.size();

//                        mSearchOutStorageListForLeaders.clear();
                        mSearchOutStorageListForLeaders.addAll(searchOutStorageListForLeaders);
                        mAdapter.notifyDataSetChanged();
                        showData();

                    }
                } else {
//                    hideData();
                    showMessage("没有更多数据");

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                hideData();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                hideData();

            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    private void showData() {
        mEmptyLayout.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
    }

    private void hideData() {
        mEmptyLayout.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void flowingDrawerClose() {
        closeMenu();
    }

    @Override
    public void search(String sid, String proid, String projectname, String purchaseid, String material, String suppliername, String targetproject, String outBeginTime, String outEndTime) {
        mStart = 1;

        mSid = sid;
        mProid = proid;
        mProjectName = projectname;
        mPurchaseid = purchaseid;
        mMaterial = material;
        mSuppliername = suppliername;
        mTargetproject = targetproject;
        mOutBeginTime = outBeginTime;
        mOutEndTime = outEndTime;

        closeMenu();
        hideData();
        mSearchOutStorageListForLeaders.clear();
        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), sid, proid, projectname, purchaseid, material, suppliername, targetproject, outBeginTime, outEndTime);
    }

    public void closeMenu() {
        mDrawer.closeDrawer(GravityCompat.END);
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerChuKuQingKuangComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .chuKuQingKuangModule(new ChuKuQingKuangModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_chu_ku_qing_kuang; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_chu_ku_qing_kuang));
//        getChuKuQingKuangData()
        initEmpty();
        initRefreshLayout();
        initBtnRight();
        initDrawer();
        initRecyclerView();
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);
        mChuKuQingKuangType = getIntent().getStringExtra("chu_ku_qing_kuang_type");

        getData(mSharedPreferencesHelper.getString(BaseConstants.UID), "", "", "", "", "", "", "", "", "");

    }

    private void initEmpty() {
        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(com.xiaoxing.zhinenghuacangku.R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
    }

    private void initBtnRight() {
        mBtnRight.setText("筛选");
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMenu();
            }
        });
    }

    private void initDrawer() {
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

        menuHeaderView = new ChuKuQingKuangRightSideslipLay(ChuKuQingKuangActivity.this, this, mSharedPreferencesHelper.getString(BaseConstants.UID), mSharedPreferencesHelper, mChuKuQingKuangType);
        navigationView.addView(menuHeaderView);

        menuHeaderView.setCloseMenuCallBack(new ChuKuQingKuangRightSideslipLay.CloseMenuCallBack() {
            @Override
            public void setupCloseMean() {
                closeMenu();
            }
        });
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 20, getResources().getColor(R.color.public_client_line_color)));

        mAdapter = new ChuKuQingKuangAdapter(this, mSearchOutStorageListForLeaders, this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

//                ArmsUtils.makeText(getContext(), "position=0" + position);
            }
        });
    }

    public void openMenu() {
        mDrawer.openDrawer(GravityCompat.END);
    }

    private List<ZuiXinXiaoXi.DataBean> loadModels() {
        List<ZuiXinXiaoXi.DataBean> addressLists = new ArrayList<>();


        ZuiXinXiaoXi.DataBean addressList = new ZuiXinXiaoXi.DataBean();
        addressList.setName("组织签署承诺书的通知");
        addressList.setPublicTime("2018-03-16");
        addressLists.add(addressList);

        ZuiXinXiaoXi.DataBean addressList1 = new ZuiXinXiaoXi.DataBean();
        addressList1.setName("关于物资公司增值税专用发票开票信息变更的通知");
        addressList1.setPublicTime("2017-11-23");
        addressLists.add(addressList1);

        ZuiXinXiaoXi.DataBean addressList2 = new ZuiXinXiaoXi.DataBean();
        addressList2.setName("关于协议库存合同支付比例调整的通知");
        addressList2.setPublicTime("2019-09-16");
        addressLists.add(addressList2);

        ZuiXinXiaoXi.DataBean addressList3 = new ZuiXinXiaoXi.DataBean();
        addressList3.setName("组织签署承诺书的通知");
        addressList3.setPublicTime("2018-03-16");
        addressLists.add(addressList3);


        return addressLists;
    }

    private void getChuKuQingKuangData() {
        mPresenter.getChuKuQingKuangData();
    }

    @Override
    public void getChuKuQingKuangDataSuccess(ChuKuQingKuang entityData) {


    }

    @Override
    public void fenMa(SearchOutStorageListForLeader item) {

        if (mPrinterUtil.selectPrinterCheck()) {
            showEditTextDialog(item);
        } else {
            showMessage("打印机未连接");
        }
    }

    private void showEditTextDialog(SearchOutStorageListForLeader item) {
        String nums_to_print = item.getNums_to_print();
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getContext());
        builder.setTitle("分码数量")
                .setPlaceholder("填写分码数量")
                .setDefaultText(nums_to_print)
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        try {
                            CharSequence text = builder.getEditText().getText();
                            if (text != null) {
                                if (text.length() > 0) {
                                    if (!TextUtils.isEmpty(nums_to_print)) {
                                        if (Double.parseDouble(text.toString()) <= Double.parseDouble(nums_to_print)) {
                                            outStoreCutMidQRCreateAndPrint(item.getOut_storage_id(), item.getMid(), mSharedPreferencesHelper.getString(BaseConstants.UID), text.toString(), item);
                                            dialog.dismiss();
                                        } else {
                                            showMessage("分码数量不能大于" + nums_to_print);
                                        }

                                    }
                                } else {
                                    showMessage("请填写分码数量");
                                }
                            } else {
                                showMessage("请填写分码数量");
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    /**
     * @param
     * @return
     * @method
     * @description 调用接口，生成分码，并打印
     * @date: 2020/11/24 0024 11:33
     * @author: 小星
     */
    private void outStoreCutMidQRCreateAndPrint(String out_storage_id, String mid, String uid, String nums, SearchOutStorageListForLeader item) {

        showLoading();
        String methodName = "OutStoreCutMidQRCreateAndPrint";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("out_storage_id", out_storage_id);
        params.put("mid", mid);
        params.put("uid", uid);
        params.put("nums", nums);


        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                    if (Integer.parseInt(result) > 0) {
                        showMessage("开始打印二维码");
                        printBigQRcodeOriention(result, item.getProjectname(), item.getMaterial(), nums, item.getOuttime(), item.getProid());
                    } else {
                        showMessage("生成分码失败，result=" + result);
                    }
                } else {
                    showMessage("生成分码失败，result=" + result);
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
                hideData();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
                hideData();

            }
        }, getAapiUserName(), getApiPwd());


    }

    private void printBigQRcodeOriention(String content, String orderNo, String name, String num, String time, String proid) {

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.setItemHorizontalAlignment(LPAPI.ItemAlignment.LEFT);
        api.setItemOrientation(180);

        api.startJob(50 * 100, 50 * 100);//48, 50
//        api.setItemOrientation(180);

        // 开始一个页面的绘制，绘制二维码
        if (name.length() > 19) {
            if (name.substring(19).length() > 23) {
                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(42), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(19, 42), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("核对序号:" + content, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("订单号:" + orderNo, 46 * 100, 22 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.draw2DQRCode(content, 14 * 100, 23 * 100, 17 * 100);//  9, 10, 20,30
            } else {
                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(19), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("核对序号:" + content, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("订单号:" + orderNo, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.draw2DQRCode(content, 14 * 100, 20 * 100, 20 * 100);//  9, 10, 20,30
            }

        } else {
            api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("核对序号:" + content, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("订单号:" + orderNo, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.draw2DQRCode(content, 14 * 100, 17 * 100, 20 * 100);//  9, 10, 20,30
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);

    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {

    }

    @Override
    public void onPrintProgress(String info) {

    }

    @Override
    public void onPrinterDiscovery(String info) {

    }

    @Override
    public void connectSuccess(String info) {

    }

    @Override
    public void Connecting(String info) {

    }

    @Override
    public void connectFail(String info) {

    }

    @Override
    public void printSuccess() {

    }

    @Override
    public void printFail() {

    }
}
